function ismobile() {
    //判断访问终端
    var browser = {
        versions: function () {
            var u = navigator.userAgent, app = navigator.appVersion;
            return {
                trident: u.indexOf('Trident') > -1, //IE内核
                presto: u.indexOf('Presto') > -1, //opera内核
                webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
                gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,//火狐内核
                mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
                ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
                android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, //android终端
                iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
                iPad: u.indexOf('iPad') > -1, //是否iPad
                webApp: u.indexOf('Safari') == -1, //是否web应该程序，没有头部与底部
                weixin: u.indexOf('MicroMessenger') > -1, //是否微信 （2015-01-22新增）
                qq: u.match(/\sQQ/i) == " qq" //是否QQ
            };
        }(),
        language: (navigator.browserLanguage || navigator.language).toLowerCase()
    };

    if (browser.versions.mobile == true) {
        if (browser.versions.iPhone == true) {
            return '1';
        } else if (browser.versions.android == true) {
            return '0';
        }
    } else {

    }
}


//$(function () {
//
//    getOrderCode();

var Date1, oldEndDate, newEndDate;

//delayAjax(30, "100006540394", "1C57D351-6D36-0357-EC7F-F6E8426302E5", 200)

//});

var isMobile = ismobile();

function getOrderCode() {//通知ios和安卓传参

    if (isMobile == 1) {

        CallOrderDelayedModel.jsCallOCWithSendId();

    } else if (isMobile == 0) {

        window.android.getAndroidId(JSON.stringify("oo"));
    }
}

if (isMobile == 0) {

    window.android.getAndroidId(JSON.stringify("oo"));
}

function WebViewDidFinishLoad() {

    var message = {

        "VcWay": "SendId"
    };

    window.webkit.messageHandlers.CallOrderDelayedModel.postMessage(message);
}

function receive_android_projectid(k) {//接受安卓参数

    var obj = $.parseJSON(k);

    delayAjax(obj.uid, obj.order_code, obj.TOKEN, obj.port, obj.belong_model);

    Date1 = obj.date
}

function receiveiOSVcData(i) {//接受ios参数

    var obj = $.parseJSON(i);

    delayAjax(obj.uid, obj.order_code, obj.TOKEN, obj.port, obj.belong_model);

    Date1 = obj.date
}

function delayAjax(uid, code, token, port, belong_model) {//订单详情接口 渲染页面

    $.ajax({

        type: "POST",

        url: url + "users/orderinfo",

        dataType: "json",

        //anysc: false,

        data: {
            "uid": uid,

            "order_code": code
        },

        beforeSend: function (xhr) {

            xhr.setRequestHeader("TOKEN", token);
        },
        success: function (data) {

            //console.log(data)

            if (data.data.codes == "200") {

                var result = data.data.data;

                if (result.belong_model == 100) {

                    if (!result.meal_info) {

                        result.meal_info = {};

                    }
                    result.start_time = timeFormat(result.start_time);

                    result.end_time = timeFormat(result.end_time);

                    var html = template("productDetailTpl", data)
                }

                $("#order_body").html(html);

                if (isiphoneX) {

                    $("#order_footer").css("padding-bottom", "0.484rem");

                }

                $(".date").html("日期：" + Date1)

            } else {

                if (isMobile == 1) {

                    window.webkit.messageHandlers.CallOrderDelayedModel.postMessage({
                        "VcData": data.data.msg,
                        "VcWay": "ShowMessage"
                    });

                } else if (isMobile == 0) {

                    window.android.toastMsg(data.data.msg);
                }
            }
            //invite(uid)
            //使用时间
            //$(".order_start").html(timeFormat(data.data.data.start_time));
            //$(".order_end").html(timeFormat(data.data.data.end_time));

            //点击订单中的结束时间，获取ios和Android的信息
            $(".order_time").on("touchstart", ".order_end", function () {

                if (data.data.data.postpone_status == 100) {

                    oldEndDate = data.data.data.end_time.replace(/-/g, "/");

                    var timestampEnd = Date.parse(new Date(oldEndDate));//结束时间    时间戳

                    timestampEnd = timestampEnd / 1000;

                    var timestampNow = Date.parse(new Date());//当前时间     时间戳

                    timestampNow = timestampNow / 1000;

                    var timesbefor = timestampEnd - (48 * 60 * 60);//结束时间前的48小时

                    if (timestampNow >= timesbefor && timestampNow <= timestampEnd) {

                        if (isMobile == 1) {

                            window.webkit.messageHandlers.CallOrderDelayedModel.postMessage({"VcWay": "EndDate"});

                        } else if (isMobile == 0) {

                            window.android.endShowToast("ooo");
                        }
                    } else {

                        if (isMobile == 1) {

                            window.webkit.messageHandlers.CallOrderDelayedModel.postMessage({
                                "VcData": "只能在结束时间前48小时内申请延时",
                                "VcWay": "ShowMessage"
                            });

                        } else if (isMobile == 0) {

                            window.android.toastMsg("只能在结束时间前48小时内申请延时");
                        }
                    }
                } else {

                    if (isMobile == 1) {

                        window.webkit.messageHandlers.CallOrderDelayedModel.postMessage({
                            "VcData": "只能延时一次",
                            "VcWay": "ShowMessage"
                        });

                    } else if (isMobile == 0) {

                        window.android.toastMsg("只能延时一次");
                    }
                }
            });
            //点击延迟订单    提交订单
            $(".submit").on("click", function () {

                if ($(".order_price").html().slice(5) > 0) {

                    var time = $(".order_end").html().replace(/-/g, "/");//结束时间

                    postpone(uid, timeFormatDate22(time), code, token);

                } else {

                    if (isMobile == 1) {

                        window.webkit.messageHandlers.CallOrderDelayedModel.postMessage({
                            "VcData": "请选择延期的结束时间",
                            "VcWay": "ShowMessage"
                        });

                    } else if (isMobile == 0) {

                        window.android.toastMsg("请选择延期的结束时间");
                    }
                }
            });
            //点击跳转协议
            $(".xieyi").on("click", function () {

                var json = {
                    "url": "https://viewapi.aipics.cn/view_h5/agreement/lease.html",

                    "titleName": "用户租赁协议"
                };

                if (isMobile == 1) {

                    var message = {

                        "VcData": json,

                        "VcName": "PublicWeb",

                        "VcWay": "PushVCName"
                    };

                    window.webkit.messageHandlers.CallOrderDelayedModel.postMessage(message);


                } else if (isMobile == 0) {

                    window.android.toRule("...")
                }
            });
        },
        error: function (info) {

            if (isMobile == 1) {

                window.webkit.messageHandlers.CallOrderDelayedModel.postMessage({
                    "VcData": "请检查网络",
                    "VcWay": "ShowMessage"
                });

            } else if (isMobile == 0) {

                window.android.toastMsg("请检查网络");
            }

        }
    })
}

//自取地址
function invite(uid) {

    $.ajax({

        type: "POST",

        url: url + "users/enterpriseinfo",

        dataType: "json",

        //anysc: false,

        data: {uid: uid},

        success: function (data) {


            if (data.data.codes == "200") {

                $(".address_customer").html(data.data.data.take_address);

                // alert(data.data.data.take_address)

                $(".address_contacts").html(data.data.data.link_person);

                $(".address_phone").html(data.data.data.link_mobile);

            } else {
                // alert(data.data.msg)
            }
        },
        error: function (info) {

            if (isMobile == 1) {

                window.webkit.messageHandlers.CallOrderDelayedModel.postMessage({
                    "VcData": "请检查网络",
                    "VcWay": "ShowMessage"
                });

                //CallOrderDelayedModel.jsCalliOSWithShowMessage("请检查网络");

            } else if (isMobile == 0) {

                window.android.toastMsg("请检查网络");
            }
        }
    })
}
//格式化时间
function timeFormat(time) {//201712271200

    var y = time.substring(0, 4);

    var m = time.substring(4, 6);

    var d = time.substring(6, 8);

    var h = time.substring(8, 10);

    var s = time.substring(10, 12);

    return (y + "-" + m + "-" + d + " " + h + ":" + s)
}
//格式化时间
function timeFormatDate(timeStamp) {

    var tmpTime = Date.parse(new Date(timeStamp));

    Date.prototype.format = function (format) {
        var date = {
            "M+": this.getMonth() + 1,
            "d+": this.getDate(),
            "h+": this.getHours(),
            "m+": this.getMinutes(),
            "s+": this.getSeconds(),
            "q+": Math.floor((this.getMonth() + 3) / 3),
            "S+": this.getMilliseconds()
        };
        if (/(y+)/i.test(format)) {
            format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
        for (var k in date) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1
                    ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
            }
        }
        return format;
    }

    var newDate = new Date();
    newDate.setTime(tmpTime);
    return newDate.format('yyyy-MM-dd hh:mm');
}
//格式化时间201801061240
function timeFormatDate22(timeStamp) {

    var tmpTime = Date.parse(new Date(timeStamp));

    Date.prototype.format = function (format) {
        var date = {
            "M+": this.getMonth() + 1,
            "d+": this.getDate(),
            "h+": this.getHours(),
            "m+": this.getMinutes(),
            "s+": this.getSeconds(),
            "q+": Math.floor((this.getMonth() + 3) / 3),
            "S+": this.getMilliseconds()
        };
        if (/(y+)/i.test(format)) {
            format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
        for (var k in date) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1
                    ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
            }
        }
        return format;
    }

    var newDate = new Date();
    newDate.setTime(tmpTime);
    return newDate.format('yyyyMMddhhmm');
}

var order_start;

function receiveiOSOrderStart(a) {

    order_start = $(".order_start").html(a['startDate']);
}

function receive_android_orderStart(k) {

    order_start = $(".order_start").html(k);
}

function receiveiOSOrderEnd(a) {

    if (a) {

        $(".order_end").html(a);

        newEndDate = a;

        time(a);

    } else {

        $(".order_end").html("请选择延期的结束时间");

    }

}

function receive_android_endDate(k) {

    $(".order_end").html(k);

    newEndDate = k;

    time(k);
}

function time(newEndDate) {

    //获取改变以后的结束时间  新的结束时间-开始时间  不能大于90天   如果大于90天 结束时间按最大值算  【计算延时金额（最新结束时间-改变前的结束时间）*租金】

    var newEnd = newEndDate.replace(/-/g, "/");

    var oldStart = $(".order_start").html().replace(/-/g, "/");

    newEnd = Date.parse(new Date(newEnd)) / 1000;

    oldStart = Date.parse(new Date(oldStart)) / 1000;


    var months = mGetDate(1) + mGetDate(2) + mGetDate(3);//最长三个月延时

    if ((newEnd - oldStart) > (months * 24 * 60 * 60)) {

        newEnd = oldStart + (months * 24 * 60 * 60);//改变后的结束时间的时间戳
        var a = newEnd * 1000;

        $(".order_end").html(timeFormatDate(a));

        getParams(timeFormatDate(a).replace(/-/g, "/"));


    } else {//小于90天 直接展示    【计算延时金额】

        var endTime = newEndDate.replace(/-/g, "/");

        getParams(endTime)
    }
}
//计算价格
function Amount(start_time, end_time, number, price) {

    // alert(start_time+"---"+ end_time+"---"+ number+"---"+ price)

    var diffSecond = (end_time - start_time) / 1000;

    var diffHour = diffSecond / 3600;

    var diffDay = Math.floor(diffSecond / (24 * 3600));

    // alert(diffHour)

    var remainderMoney = 0;

    if (diffHour > 24) {

        remainderHour = Math.ceil(diffHour % 24);

        if (remainderHour > 8) {

            diffDay += 1;

        } else {

            remainderMoney = (price / 8) * remainderHour;
        }

        return Number((diffDay * price + remainderMoney) * number).toFixed(2);

    } else {

        return Number(price * number).toFixed(2);
    }

}
//数量+ - 套餐  时间 放在一个类里面   时间要时间戳
function getParams(endTime) {

    var mealPrice = Number($(".meal .price").html().substring(0, $(".meal .price").html().length - 2));

    var startTime = oldEndDate;

    var num = $(".order_goodsMsg .num").html().slice(3);

    var timestamp1 = Date.parse(new Date(startTime.replace(/-/g, "/")));//将开始时间转换为时间戳

    var timestamp2 = Date.parse(new Date(endTime.replace(/-/g, "/")));//将结束时间转换为时间戳

    if (timestamp1 && timestamp2) {

        var totalAmount = Amount(timestamp1, timestamp2, num, mealPrice);

        $("#order_footer .order_price").html("实付款:￥" + totalAmount);

        $(".moneyDetail .proTotal").html(totalAmount);
    }

}
//申请延期
function postpone(uid, postpone_time, order_code, token) {

    //alert(uid+"---"+postpone_time+"---"+ order_code+"---"+ token)

    $.ajax({

        type: "POST",

        url: url + "users/applypostpone",

        dataType: "json",

        //anysc: false,

        data: {
            "uid": uid,

            "postpone_time": postpone_time,

            "order_code": order_code
        },

        beforeSend: function (xhr) {

            xhr.setRequestHeader("TOKEN", token);
        },
        success: function (data) {

            if (data.data.codes == "200") {

                if (isMobile == 1) {

                    var message = {

                        "VcData": {"order_code": data.data.data.order_code},

                        "VcName": "ListPay",

                        "VcWay": "PushPayVC"
                    };

                    window.webkit.messageHandlers.CallOrderDelayedModel.postMessage(message);

                } else if (isMobile == 0) {

                    window.android.jumpToProjectPayOrder(data.data.data.order_code);
                }
            } else {

                if (isMobile == 1) {

                    window.webkit.messageHandlers.CallOrderDelayedModel.postMessage({
                        "VcData": data.data.msg,
                        "VcWay": "ShowMessage"
                    });

                } else if (isMobile == 0) {

                    window.android.toastMsg(data.data.msg);
                }
                return false

            }
        },
        error: function (info) {

            if (isMobile == 1) {

                window.webkit.messageHandlers.CallOrderDelayedModel.postMessage({
                    "VcData": "请检查网络",
                    "VcWay": "ShowMessage"
                });

            } else if (isMobile == 0) {

                window.android.toastMsg("请检查网络");
            }

        }
    })
}
//获取当前月的天数，下月，下下月的总和
function mGetDate(n) {

    var date = new Date();

    var year = date.getFullYear();

    var month = date.getMonth() + n;

    if (month > 12) {

        year++;

        month = month - 12;
    }
    var d = new Date(year, month, 0);

    return d.getDate();
}

